package com.college.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.college.dao.CourseDetailsDao;
import com.college.domain.CourseDetails;

public class CourseDetailsDaoImpl implements CourseDetailsDao{
	
	private static String ADD_COURSE_QUERY="FROM CourseDetails course WHERE course.courseCode =";
	private static String UPDATE_COURSE_QUERY="update CourseDetails c set c.courseName=?,c.courseBranch=?,c.courseDuration=?,c.courseIntake=? where c.courseCode=";
	private static String GET_COURSE_QUERY="FROM CourseDetails course WHERE course.courseCode =";
	
	private static HibernateTemplate hibernateTemplate;
	   
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}
	
	public boolean addCourse(CourseDetails courseDetails){
		
		@SuppressWarnings("unchecked")
		List<CourseDetails> courseList=hibernateTemplate.find( ADD_COURSE_QUERY+ courseDetails.getCourseCode());

		if(courseList.size()==0){
			hibernateTemplate.saveOrUpdate(courseDetails);
			return true;
		}else{
			return false;
		}

	}

	@Override
	public CourseDetails getCourseDetailsForCourseCode(String courseCode) {

		List<CourseDetails> courseList=hibernateTemplate.find( GET_COURSE_QUERY + courseCode);
	
		if(courseList.size()!=0){
	    return courseList.get(0);
		}else{
			return null;
		}
		
	}

	@Override
	public boolean updateCourse(CourseDetails courseDetails) {
		
		SessionFactory sessionFactory= hibernateTemplate.getSessionFactory();
		Session session = sessionFactory.openSession();
		
		 Query qry = session.createQuery(UPDATE_COURSE_QUERY+courseDetails.getCourseCode());
		
		 qry.setParameter(0,courseDetails.getCourseName());
		 qry.setParameter(1,courseDetails.getCourseBranch());
		 qry.setParameter(2,courseDetails.getCourseDuration());
		 qry.setParameter(3,courseDetails.getCourseIntake());
		 
		 int res = qry.executeUpdate();
		session.close();
		sessionFactory.close();
	
		if(res>0){
			return true;
		}else{
			return false;
		}
	
	}

}
